package br.skytef.stmanager.daos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import br.skytef.stmanager.entities.ClienteContatoEntity;
import br.skytef.stmanager.utils.Pool;

public class ClienteContatoDao {
	/**
	 * Variável para conexão, obtido através de um Pool(br.skytef.stmanager.utils.Pool)
	 */
	private static Connection conexao = null;	
	/**
	 * Inserir ClienteContato
	 * @param clienteContato
	 */
	private static String erro;
	public static String getErro() {return erro;}
	
	public boolean inserirClienteContato(ClienteContatoEntity clienteContato){
		try {
			conexao = Pool.getConnection();
			String query = "INSERT INTO clienteContato (contato_Id,cliente_idCliente,data_inclusao)"
					+ "VALUES (?,?,?);";
			PreparedStatement preparedStmt = conexao.prepareStatement(query);
			preparedStmt.setInt					(1,clienteContato.getContatoId());
			preparedStmt.setInt					(2,clienteContato.getClienteId());
			preparedStmt.setTimestamp			(3,clienteContato.getDataInclusao());
			preparedStmt.execute();	
			conexao.close();
			return true;


		} catch (SQLException e) {
			System.out.println("SQL erro: "+ e);
			erro=e.toString();
			return false;
		}catch (ClassCastException e) {
			System.out.println("Classe erro: "+ e);
			erro=e.toString();
			return false;
		} catch (Exception e) {
			System.out.println("Geral erro: "+ e);
			erro=e.toString();
			return false;
		}
	
	}
	
	
		
	public List <ClienteContatoEntity> listarContato(int idCliente){
		List <ClienteContatoEntity> contatos = null;
		ClienteContatoEntity contato;
		try {
			conexao = Pool.getConnection();
			Statement st = conexao.createStatement();
			ResultSet rs = st.executeQuery("SELECT C.nome,CC.contato_id FROM contato as C INNER JOIN clienteContato as CC ON C.id = CC.contato_id  WHERE CC.cliente_idCliente = "+ idCliente +";");
			if (rs.next()) {   
				contatos = new ArrayList<ClienteContatoEntity>();
				do {                    
					contato = new ClienteContatoEntity();
					contato.setNome(rs.getString("nome"));
					contato.setContatoId(rs.getInt("contato_id"));
					contatos.add(contato);
				} while (rs.next());
			}
			conexao.close();
		} catch (SQLException e) {
			System.out.println("SQL erro: "+ e);
		} catch (Exception e) {
			System.out.println("Geral erro: "+ e);
		}
		return contatos;
	
	}
}
